import { ref, computed, reactive } from 'vue'
import { defineStore } from 'pinia'
import { UserControllerService, type LoginUserVO, type UserLoginRequest } from '@/servers'
import { ResponseCode } from '@/servers/core/request'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'

export default defineStore('user', () => {
  const currentUser = reactive<LoginUserVO>({})
  const router = useRouter()
  const login = async (data: UserLoginRequest) => {
    const res = await UserControllerService.userLoginUsingPost(data)
    if (res.code == ResponseCode.SUCCESS) {
      window.localStorage.setItem('isLogin', 'true')
      Object.assign(currentUser, res.data)
      router.push('/')
      Message.success({ content: '登录成功' })
    }
  }
  const getCurrentUser = async () => {
    const res = await UserControllerService.getLoginUserUsingGet()
    if (res.code == ResponseCode.SUCCESS) {
      window.localStorage.setItem('isLogin', 'true')
      Object.assign(currentUser, res.data)
    }
  }

  // 退出登录
  const logout = async () => {
    const res = await UserControllerService.userLogoutUsingPost()
    if (res.code == ResponseCode.SUCCESS) {
      window.localStorage.setItem('isLogin', 'false')
      Object.assign(currentUser, {})
      Message.success({ content: '退出登录' })
    }
  }
  return { currentUser, login, getCurrentUser, logout }
})
